<?php
/**
 * 微信支付
 */

namespace app\server;


use EasyWeChat\Factory;

class WxPay {
    protected $app;

    public function __construct() {
        $config = config('wxpay');
        $this->app = Factory::payment($config);
    }

    /**
     * 生成订单
     * @param $data
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function makeOrder($data) {
        return $this->app->order->unify($data);
    }

    /**
     * 获取支付配置参数信息
     * @param $prepay_id
     * @return array|string
     */
    public function bridgeConfig($prepay_id) {
        return $this->app->jssdk->bridgeConfig($prepay_id,false);
    }

    /**
     * 回调方法
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     */
    public function notify() {
        $response = $this->app->handlePaidNotify(function ($message, $fail) {
            $order = Db::name('order')->where(['order' => $message['out_trade_no']])->find();
            if (!$order || $order['status'] == 2) { // 如果订单不存在 或者 订单已经支付过了
                return true;
            }

            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    //成功处理操作 略
                    //$message['out_trade_no']　　商户订单号

                    // 用户支付失败
                } elseif ($message['result_code'] === 'FAIL') {
                    return true;
                }
            } else {
                return false;
            }
        });
        return $response;
    }
}
